package com.wwwarehouse.carddesk.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.carddesk.R;
import com.wwwarehouse.carddesk.common.CardDeskCommon;
import com.wwwarehouse.carddesk.constant.CardDeskConstant;
import com.wwwarehouse.carddesk.eventbus_event.CardDeskFunctionFilterEvent;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.adapter.carddesk.MyFragmentPagerAdapter;
import com.wwwarehouse.common.adapter.pop.BubblePopAdapter;
import com.wwwarehouse.common.bean.filter.FilterBean;
import com.wwwarehouse.common.bean.response.CardDeskFunctionResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.CustomViewPagerInternal;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.SlideBarView;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.fragment.DeskDrawerMultipleFragment;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tripartite_widget.viewindicator.CirclePageIndicator;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.greenrobot.event.EventBus;

@Route(path = "/carddesk/TaskTabFragment")
public class FunctionTabFragment extends BaseFragment {
    private View mRootView;

    private LinearLayout mResultLayout;
    private LinearLayout mEmptyLayout;
    private ImageView mEmptyImg;
    private TextView mEmptyTxt;

    private StateLayout mStateLayout;
    private ElasticScrollView mElasticScrollView;
    private CustomViewPagerInternal mCustomViewPagerInternal;
    private CirclePageIndicator mCirclePageIndicator;
    private SlideBarView mSlideBarView;
    private List<Fragment> mFragmentList;

    private String mBuId;
    private String mOrderSort;
    private String mOrderType;
    private String mSearchText;
    private Set<String> mTaskTagSet;

    private List<FilterBean> mFilterList;
    private List<FilterBean> mFunctionUnitList;

    private List<CardDeskFunctionResponseBean.BusinessBean> mBusinessDetailsList;
    private List<CardDeskFunctionResponseBean.TaskTagBean> mTaskTagList;

    private static final int REQUEST_GET_FUNCTION_INFO = 0;

    public static final int LIMIT = 15;
    public static final int PAGE = 1;

    public static final String KEY_FUNCTION_BU_ID = "key_function_bu_id";
    public static final String KEY_FUNCTION_ORDER_SORT = "key_function_order_sort";
    public static final String KEY_FUNCTION_ORDER_TYPE = "key_function_order_type";
    public static final String KEY_FUNCTION_SEARCH_TEXT = "key_function_search_text";
    public static final String KEY_FUNCTION_TAG_SET = "key_function_tag_set";
    public static final String KEY_FUNCTION_PAGE = "key_function_page";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_function_tab, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initData();
        initEvent();
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        return null;
    }

    private void initView() {
        ((BaseCardDeskActivity) mActivity).setFunctionUnitText(R.string.all_business_unit);

        mResultLayout = findView(mRootView, R.id.ll_result);
        mEmptyLayout = findView(mRootView, R.id.ll_empty);
        mEmptyImg = findView(mRootView, R.id.iv_empty);
        mEmptyTxt = findView(mRootView, R.id.tv_empty);

        mStateLayout = findView(mRootView, R.id.sl_layout);

        //ProgressView向上偏移 1/2 CirclePageIndicator的高度，防止外层ProgressView和内层ProgressView发生错位偏移
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mStateLayout.getProgressviewLayoutparam();
        params.bottomMargin += ConvertUtils.dip2px(mActivity, 19);
        mStateLayout.showProgressView(false);

        mElasticScrollView = findView(mRootView, R.id.esv_elastic);
        mCustomViewPagerInternal = findView(mRootView, R.id.vpi_invite);
        mCirclePageIndicator = findView(mRootView, R.id.cpi_indicator);
        mSlideBarView = findView(mRootView, R.id.sbv_slide);

        mFragmentList = new ArrayList<>();

        mBuId = "";
        mOrderSort = "";
        mOrderType = "";
        mSearchText = "";
        mTaskTagSet = new HashSet<>();

        mFilterList = new ArrayList<>();

        mFunctionUnitList = new ArrayList<>();
    }

    private void initData() {
        getFunctionInfo();
    }

    private void initEvent() {
        mElasticScrollView.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {
                //判断是否显示搜索框上的业务单位按钮
                if (mFunctionUnitList.size() > 2) {
                    //显示搜索框上的业务单位按钮
                    ((BaseCardDeskActivity) mActivity).showFunctionUnitText();
                } else {
                    //隐藏搜索框上的业务单位按钮
                    ((BaseCardDeskActivity) mActivity).hideFunctionUnitText();
                }

                ((BaseCardDeskActivity) mActivity).downPull_4();
            }

            @Override
            public void onUpPull() {

            }
        });
    }

    @Override
    public void functionUnitClick(View anchor) {
        PopUpUtils.showBubbleFunctionUnit(anchor, mActivity, mFunctionUnitList, new BubblePopAdapter.OnPopListClickListener() {
            @Override
            public void setOnItemClickListener(int position, View view) {
                ((BaseCardDeskActivity) mActivity).setFunctionUnitText(mFunctionUnitList.get(position).getText());

                if (position == 0) {
                    mBuId = "";
                } else {
                    mBuId = mBusinessDetailsList.get(position - 1).getBuId();
                }

                getFunctionInfo();
            }
        }, ConvertUtils.dip2px(mActivity, 14), anchor.getHeight() + ConvertUtils.dip2px(mActivity, 40));
    }

    @Override
    public void setTitle() {

    }

    @Override
    public void requestDatas() {

    }

    public String getOrderSort() {
        return mOrderSort;
    }

    public void setOrderSort(String orderSort) {
        this.mOrderSort = orderSort;
    }

    public String getOrderType() {
        return mOrderType;
    }

    public void setOrderType(String orderType) {
        this.mOrderType = orderType;
    }

    public String getSearchText() {
        return mSearchText;
    }

    public void setSearchText(String searchText) {
        this.mSearchText = searchText;
    }

    public Set<String> getTaskTagSet() {
        return mTaskTagSet;
    }

    public void setTaskTagSet(Set<String> taskTagSet) {
        this.mTaskTagSet = taskTagSet;
    }

    public List<CardDeskFunctionResponseBean.TaskTagBean> getTaskTagList() {
        return mTaskTagList;
    }

    public void setTaskTagList(List<CardDeskFunctionResponseBean.TaskTagBean> taskTagList) {
        this.mTaskTagList = taskTagList;
    }

    public void getFunctionInfo(boolean... isSearch) {
        if (isSearch.length > 0 && isSearch[0]) {
            mStateLayout.showProgressView(false);
        }

        Map map = new HashMap<>();

        map.put("actionType", "C");

        if (!TextUtils.isEmpty(mBuId)) {
            map.put("buId", mBuId);
        }

        map.put("limit", LIMIT);
        map.put("page", PAGE);
        map.put("orderSort", mOrderSort);
        map.put("orderType", mOrderType);
        map.put("searchText", mSearchText);
        map.put("taskTags", mTaskTagSet);

        NoHttpUtils.httpPost(CardDeskConstant.URL_GET_FUNCTION_INFO, map, mOnResponseListener, REQUEST_GET_FUNCTION_INFO);
    }

    public void initDrawerLayout() {
        DeskDrawerMultipleFragment deskDrawerMultipleFragment = DeskDrawerMultipleFragment.newInstance(getString(R.string.function_category), mFilterList, 2);
        ((BaseCardDeskActivity) mActivity).setDrawerLayout(deskDrawerMultipleFragment);
    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_GET_FUNCTION_INFO:
                    if ("0".equals(commonClass.getCode())) {
                        CardDeskFunctionResponseBean cardDeskFunctionResponseBean = JSON.parseObject(commonClass.getData().toString(), CardDeskFunctionResponseBean.class);
                        mOrderSort = cardDeskFunctionResponseBean.getOrderSort();
                        mOrderType = cardDeskFunctionResponseBean.getOrderType();
                        mTaskTagList = cardDeskFunctionResponseBean.getTaskTags();
                        mBusinessDetailsList = cardDeskFunctionResponseBean.getBuIds();

                        if ("DESC".equals(mOrderSort) && "TASK_UNIT_RATE".equals(mOrderType)) {
                            EventBus.getDefault().post(new CardDeskFunctionFilterEvent(2));
                        } else {
                            EventBus.getDefault().post(new CardDeskFunctionFilterEvent(3));
                        }

                        if (mTaskTagList != null) {
                            //有筛选条件
                            if (mTaskTagSet.size() > 0) {
                                for (String taskTagValue : mTaskTagSet) {
                                    for (CardDeskFunctionResponseBean.TaskTagBean taskTagBean : mTaskTagList) {
                                        if (taskTagValue.equals(taskTagBean.getTagValue())) {
                                            for (FilterBean filterBean : mFilterList) {
                                                if (taskTagBean.getTagRemark().equals(filterBean.getText())) {
                                                    filterBean.setSelect(true);
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                //初始化抽屉数据
                                mFilterList.clear();

                                for (CardDeskFunctionResponseBean.TaskTagBean taskTagBean : mTaskTagList) {
                                    mFilterList.add(new FilterBean(false, taskTagBean.getTagRemark()));  //全部未选
                                }
                            }
                        }

                        initDrawerLayout();

                        //初始化业务单位数据
                        mFunctionUnitList.clear();
                        mFunctionUnitList.add(new FilterBean(false, getString(R.string.all_business_unit)));

                        if (mBusinessDetailsList != null) {
                            for (CardDeskFunctionResponseBean.BusinessBean businessBean : mBusinessDetailsList) {
                                mFunctionUnitList.add(new FilterBean(false, businessBean.getBuName()));
                            }
                        }

                        //记住选中位置
                        for (FilterBean filterBean : mFunctionUnitList) {
                            if (filterBean.getText().equals(((BaseCardDeskActivity) mActivity).getFunctionUnitText())) {
                                filterBean.setSelect(true);
                            }
                        }

                        //总共多少页
                        int total = cardDeskFunctionResponseBean.getTotal();
                        if (total == 0) {
                            if (TextUtils.isEmpty(mSearchText)) {
                                //没有请求数据
                                mResultLayout.setVisibility(View.VISIBLE);
                                mEmptyLayout.setVisibility(View.GONE);

                                mStateLayout.showEmptyView(false);
                                mStateLayout.setEmptyListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        mStateLayout.showProgressView(false);

                                        getFunctionInfo();
                                    }
                                });
                            } else {
                                //没有搜索结果
                                mResultLayout.setVisibility(View.GONE);
                                mEmptyLayout.setVisibility(View.VISIBLE);

                                mEmptyImg.setImageResource(R.drawable.search_empty);
                                mEmptyTxt.setText(R.string.invite_search_no_result);
                            }
                        } else {
                            mResultLayout.setVisibility(View.VISIBLE);
                            mEmptyLayout.setVisibility(View.GONE);

                            //结果不为空，并且数据没有变化，不刷新界面
                            if (commonClass.getData().toString().equals(CardDeskCommon.getInstance().getFunctionLastResult())) {
                                return;
                            }

                            //保存请求结果
                            CardDeskCommon.getInstance().setFunctionLastResult(commonClass.getData().toString());

                            int page = (total % 15 == 0) ? total / 15 : (total / 15 + 1);

                            mFragmentList.clear();

                            for (int i = 0; i < page; i++) {
                                FunctionDetailsFragment functionDetailsFragment = new FunctionDetailsFragment();
                                Bundle bundle = new Bundle();
                                bundle.putString(KEY_FUNCTION_BU_ID, mBuId);
                                bundle.putString(KEY_FUNCTION_ORDER_SORT, mOrderSort);
                                bundle.putString(KEY_FUNCTION_ORDER_TYPE, mOrderType);
                                bundle.putString(KEY_FUNCTION_SEARCH_TEXT, mSearchText);
                                bundle.putSerializable(KEY_FUNCTION_TAG_SET, (Serializable) mTaskTagSet);
                                bundle.putInt(KEY_FUNCTION_PAGE, (i + 1));
                                functionDetailsFragment.setArguments(bundle);

                                mFragmentList.add(functionDetailsFragment);
                            }

                            mCustomViewPagerInternal.setAdapter(new MyFragmentPagerAdapter(getChildFragmentManager(), mFragmentList));

                            if (page <= 6) {
                                if (page > 1) {
                                    mCirclePageIndicator.setVisibility(View.VISIBLE);
                                    mSlideBarView.setVisibility(View.GONE);

                                    mCirclePageIndicator.setViewPager(mCustomViewPagerInternal, 0);
                                } else {
                                    mCirclePageIndicator.setVisibility(View.GONE);
                                    mSlideBarView.setVisibility(View.GONE);
                                }
                            } else {
                                mCirclePageIndicator.setVisibility(View.GONE);
                                mSlideBarView.setVisibility(View.VISIBLE);

                                mSlideBarView.setTotalPage(page);
                                mSlideBarView.setOnSlideChange(new SlideBarView.OnSlideChange() {
                                    @Override
                                    public void onSlideChange(int page) {
                                        mCustomViewPagerInternal.setCurrentItem(page, false);
                                    }
                                });

                                mSlideBarView.setViewPagerInternal(mCustomViewPagerInternal);
                            }
                        }
                    } else {
                        mStateLayout.showSystemView(commonClass.getMsg(), false);
                        mStateLayout.setSystemListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mStateLayout.showProgressView(false);

                                getFunctionInfo();
                            }
                        });
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            mStateLayout.showNetworkView(false);
            mStateLayout.setNetworkListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mStateLayout.showProgressView(false);

                    getFunctionInfo();
                }
            });
        }

        @Override
        public void onFinish(int what) {
            mStateLayout.showContentView();
        }
    };
}
